/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sd_proj1.mainProgram;

import sd_proj1.interfaces.*;
import sd_proj1.monSolution.*;

/**
 *
 * @author PedroEee
 */
public class Artesao extends Thread {

	/**
	 *  Identificação do artesao
	 *
	 *    @serialField craftsmanId
	 *
	 */
	private final int MAX = 10;    /* storeroom nominal capacity (in number of products) */

	private int craftsmanId;
	/**
	 *  Oficina
	 *
	 *    @serialField oficina
	 */
	private IArtesao oficina;
	/**
	 *  EstadoGeral
	 *
	 *    @serialField general
	 */
	private IntArtesaosFifo general;

	/**
	 *  Instanciação do thread artesao.
	 *
	 *    @param craftsmanId identificação do artesao
	 *    @param MonitorOficina oficina
	 */
	public Artesao(int craftsmanId, IArtesao oficina, IntArtesaosFifo general) {
		this.craftsmanId = craftsmanId;
		this.oficina = oficina;
		this.general = general;
	}

	/* craftsman id */
	@Override
	public void run() {
		int np;                           /* number of products in store */
		boolean alert;                   /* low level of prime materials in store */
		while (!oficina.endOperCraftsman(craftsmanId)) {
			alert = oficina.collectMaterials(craftsmanId);           /* the craftsman gets the prime materials he needs to manufacture a product */
			if (alert) {
				general.primeMaterialsNeeded(craftsmanId); /* the craftsman phones the entrepreneur to let her know the workshop requires more prime materials */
				oficina.backToWork(craftsmanId);     /* the craftsman returns to his regular duties */
			}
			oficina.prepareToProduce(craftsmanId);                    /* the craftsman sits down and prepares things for the production of a new piece */
			shapingItUp();                   /* the craftsman works on a new piece */
			np = oficina.goToStore(craftsmanId);        /* the craftsman stores the finished product */
			if (np == MAX) /* the craftsman checks if it is transfer time */ {
				general.batchReadyForTransfer(craftsmanId);	/* the craftsman phones the entrepreneur to come get products */
			}
			oficina.backToWork(craftsmanId);          /* the craftsman returns to his regular duties */
		}
	}

	/**
	 *  O artesão trabalha sobre a peça (operação interna).
	 */
	private void shapingItUp() {
		try {
			sleep((long) (1 + 100 * Math.random()));
		} catch (InterruptedException e) {
		}
	}
}
